package com.ztesoft.zsmart.zcm.metrics.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;

import java.io.IOException;

//import java.io.ByteArrayInputStream;
//import java.io.ByteArrayOutputStream;
//import java.io.ObjectInputStream;
//import java.io.ObjectOutputStream;

public final class SerializeUtil {

    private static ObjectMapper mapper = new ObjectMapper();


    private SerializeUtil() {
        // prevent instantiation
    }

    public static byte[] serialize(Object object) {
        
        
        byte[] objByte = null;
        objByte = JSON.toJSONBytes(object, SerializerFeature.EMPTY);
//            objByte = JSON.toJSONString(object).getBytes(DEFAULT_UTF_8);
        return objByte;
        
//        ObjectOutputStream oos = null;
//        ByteArrayOutputStream baos = null;
//        try {
//            baos = new ByteArrayOutputStream();
//            oos = new ObjectOutputStream(baos);
//            oos.writeObject(object);
//            return baos.toByteArray();
//        }
//        catch (Exception e) {
//            throw new CacheException(e);
//        }
    }

    public static <T> T unserialize(byte[] bytes, Class<T> clazz) {
        
        T outObj = null;
        outObj = JSON.parseObject(bytes, clazz);
        return outObj;
        
//        
//        if (bytes == null) {
//            return null;
//        }
//        ByteArrayInputStream bais = null;
//        try {
//            bais = new ByteArrayInputStream(bytes);
//            ObjectInputStream ois = new ObjectInputStream(bais);
//            return ois.readObject();
//        }
//        catch (Exception e) {
//            throw new CacheException(e);
//        }
//        
        
    }

    public static <T> String serialize2String(T t) throws IOException {

        ObjectWriter writer = mapper.writerFor(t.getClass());
        return writer.writeValueAsString(t);

    }

    public static <T> T unserializeWithString(String json, Class<T> clazz) throws IOException {

        ObjectReader reader = mapper.reader(clazz);
        return reader.readValue(json);

    }

    public static <T> byte[] serialize2Byte(T t) throws IOException {

        ObjectWriter writer = mapper.writerFor(t.getClass());
        return writer.writeValueAsBytes(t);

    }

    public static <T> T unserializeWithByte(byte[] bytes, Class<T> clazz) throws IOException {

        ObjectReader reader = mapper.reader(clazz);
        return reader.readValue(bytes);

    }



}
